<template>
  <div class="container">
    <div>
      <el-card
        class="invoice-instructions col-1"
        shadow="never"
      >
        <div class="title">
          <h3>
            <i class="el-icon-info"></i> 充值指引:
          </h3>
        </div>

        <p class="text item">1. 企业使用已添加至平台的企业银行账户汇款至指定的服务商账户。</p>
        <p class="text item">2. 服务商账户收到汇款后系统会自动计算入账金额并计入企业账户。</p>
        <p class="text item">
          3.
          由于对公账户到账情况不定，请在法定工作日工作期间进行充值，以免充值入账延后影响企业代发出款。
        </p>
        <p class="text item red">注：请使用已添加至平台的企业银行账户进行汇款，否则平台无法自动同步资金信息至企业账户。</p>
        <p class="text item red">如有疑问请联系平台客服人员。</p>
      </el-card>
    </div>

    <el-form
      :model="addForm"
      :rules="$rules"
      class="mt-1 col-1 left grid-flex"
      label-width="120px"
      ref="addFormRef"
      status-icon
    >
      <template v-for="(item, key) in addFormKeys">
        <template v-if="key === 'MID'">
          <el-form-item
            :key="key"
            :label="$language.local('MID')"
            prop="MID"
          >
            <select-id
              :apiName="merchantApiName"
              @change="midChange"
              v-model="addForm['MID']"
              value-key="MID"
            >
              <template #options="{ options }">
                <el-option
                  :key="item.MID"
                  :label="item.MerchantName"
                  :value="item.MID"
                  v-for="item in options"
                ></el-option>
              </template>
            </select-id>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 任务编号 -->
        <template v-else-if="key === 'TSKID'">
          <el-form-item
            :key="key"
            :label="$language.local('TSKID')"
            prop="TSKID"
          >
            <!-- <xy-input disabled v-model="addForm.TSKID"></xy-input> -->
            <select-id
              :api-name="tskIdApi"
              @change="taskIdChange"
              v-model="addForm.TSKID"
            >
              <template #options="{ options }">
                <el-option
                  :key="item.ID"
                  :label="`${item.ID} - ${item.projectName} - ￥${item.Amount}`"
                  :value="item.ID"
                  v-for="item in options"
                ></el-option>
              </template>
            </select-id>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 服务商 -->
        <template v-else-if="key === 'ServiceProviderName'">
          <el-form-item
            :key="key"
            :label="$language.local('ServiceProviderName')"
            prop="ServiceProviderName"
          >
            <select-name
              @change="serviceChange"
              apiName="/api/Common/GetServiceProviderList"
              label-key="ServiceName"
              v-model="addForm.ServiceProviderName"
            ></select-name>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 收款银行 -->
        <template v-else-if="key === 'ServiceBank'">
          <el-form-item
            :key="key"
            :label="$language.local('ServiceBank')"
            prop="ServiceBank"
          >
            <select-name
              :model="serviceBanks"
              @change="serviceBankChange"
              label-key="BankName"
              v-model="addForm.ServiceBank"
            ></select-name>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 收款账号 -->
        <template v-else-if="key === 'ServiceAccountNo'">
          <el-form-item
            :key="key"
            :label="$language.local('ServiceAccountNo')"
            prop="ServiceAccountNo"
          >
            <xy-input
              class="service-account-no"
              disabled
              v-model="addForm['ServiceAccountNo']"
            ></xy-input>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 代付通道 -->
        <template v-else-if="key === 'PayChannelId'">
          <el-form-item
            :key="key"
            :label="$language.local('PayChannelId')"
            prop="PayChannelId"
          >
            <!-- <select-paychannelid
                :sid="addForm.ServiceProviderID"
                v-model="addForm[key]"
            ></select-paychannelid>-->
            <select-id
              :model="payChannelList"
              label-key="BankName"
              v-model="addForm[key]"
            ></select-id>
          </el-form-item>
        </template>
        <!-- #endregion -->

        <!-- #region 充值费率 -->
        <template v-else-if="key === 'RechargeRate'">
          <el-form-item
            :key="key"
            :label="$language.local('RechargeRate')"
            prop="RechargeRate"
          >
            <el-select v-model="addForm.RechargeRate">
              <el-option
                :label="`费率 ${toFixed2(addForm.RechargeRate)}%`"
                :value="addForm.RechargeRate"
                v-if="!addForm.Rate"
              >费率{{ toFixed2(addForm.RechargeRate) }}%</el-option>
              <el-option
                :label="`起征点以下费率 ${toFixed2(addForm.Rate)}%`"
                :value="addForm.Rate"
                v-if="addForm.Rate"
              >起征点以下费率{{ toFixed2(addForm.Rate) }}%</el-option>
              <el-option
                :label="`起征点以下费率 ${toFixed2(addForm.QZDRate)}%`"
                :value="addForm.QZDRate"
                v-if="addForm.QZDRate"
              >起征点以下费率{{ toFixed2(addForm.QZDRate) }}%</el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 服务费计算规则 -->
        <template v-else-if="key === 'ruleType'">
          <el-form-item
            :key="key"
            :label="$language.local('ruleType')"
            prop="ruleType"
          >
            <el-select
              @change="ruleTypeChange"
              disabled
              placeholder="请选择"
              v-model="addForm.ruleType"
            >
              <el-option
                :key="item.value"
                :label="item.label"
                :value="item.value"
                v-for="item in ruleTypes"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 充值金额 -->
        <template v-else-if="key === 'RechargeAmount'">
          <el-form-item
            :key="key"
            :label="$language.local('RechargeAmount')"
            prop="RechargeAmount"
          >
            <xy-decimal
              :disabled="!addForm['RechargeRate'] || !addForm['ruleType']"
              :placeholder="amountInputTips()"
              @change="rechargeChange"
              class="service-account-no"
              v-model="addForm['RechargeAmount']"
            ></xy-decimal>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 充值时间 -->
        <template v-else-if="key === 'RechargeTime'">
          <el-form-item
            :key="key"
            :label="$language.local('RechargeTime')"
            prop="RechargeTime"
          >
            <select-date v-model="addForm.RechargeTime"></select-date>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 实发金额 -->
        <template v-else-if="key === 'AccountAmount'">
          <el-form-item
            :key="key"
            :label="$language.local('AccountAmount')"
            prop="AccountAmount"
          >
            <xy-decimal
              :disabled="!addForm['RechargeRate'] || !addForm['ruleType']"
              :placeholder="amountInputTips()"
              @change="accountChange"
              class="service-account-no"
              v-model="addForm['AccountAmount']"
            ></xy-decimal>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 付款账户 -->
        <template v-else-if="key === 'PayingAccountName'">
          <el-form-item
            :key="key"
            :label="$language.local('PayingAccountName')"
            prop="PayingAccountName"
          >
            <xy-input
              clearable
              disabled
              v-model="addForm['PayingAccountName']"
            ></xy-input>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 付款银行 -->
        <template v-else-if="key === 'PayingBank'">
          <el-form-item
            :key="key"
            :label="$language.local('PayingBank')"
            prop="PayingBank"
          >
            <xy-input
              clearable
              disabled
              v-model="addForm['PayingBank']"
            ></xy-input>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 付款账户 -->
        <template v-else-if="key === 'PayingAccount'">
          <el-form-item
            :key="key"
            :label="$language.local('PayingAccount')"
            prop="PayingAccount"
          >
            <xy-input
              clearable
              disabled
              v-model="addForm['PayingAccount']"
            ></xy-input>
          </el-form-item>
        </template>
        <!-- #endregion -->
        <!-- #region 银行回单 -->
        <template v-else-if="key === 'customerReceiptUrl'">
          <el-form-item
            :key="key"
            :label="$language.local(key)"
            :prop="key"
            class="upload-file"
          >
            <!-- <xy-input v-model="addForm[key]" clearable></xy-input> -->
            <upload-image v-model="addForm[key]"></upload-image>
          </el-form-item>
        </template>
        <!-- #endregion -->

        <!-- #region 费用说明 -->
        <template v-else>
          <el-form-item
            :key="key"
            :label="$language.local(key)"
            :prop="key"
          >
            <xy-input
              clearable
              v-model="addForm[key]"
            ></xy-input>
          </el-form-item>
        </template>
        <!-- #endregion -->
      </template>
    </el-form>

    <template v-if="api.action === 'Check'">
      <el-radio-group
        class="form-footer mb-2"
        v-model="checkStatus"
      >
        <el-radio :label="1">待确认</el-radio>
        <el-radio :label="2">已确认待复核</el-radio>
        <el-radio :label="3">已复核</el-radio>
        <el-radio :label="4">无效充值</el-radio>
      </el-radio-group>
    </template>
    <div class="form-footer pb-3">
      <el-button
        @click="cancelfunc"
        size="medium"
      >返回</el-button>
      <el-button
        @click="onSubmit('addFormRef')"
        size="medium"
        type="primary"
      >确定</el-button>
    </div>
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  inject: ["toFixed2"],

  data() {
    return {
      api: new API("/api/recharge/Create"),
      tskIdApi: "/api/ServiceProject/GetList",
      merchantApiName: "/api/MerchantSign/GetList",
      checkStatus: 3,
      serviceBanks: [],
      payChannelList: [],
      rechargeRate: "",
      ruleType: "",
      ruleTypes: [
        {
          label: "A：实发金额 / （1-充值费率）",
          value: "A",
        },
        {
          label: "B：实发金额 * （1+充值费率）",
          value: "B",
        },
      ],
      addForm: {
        // _serviceproviderid: null,
        ServiceProviderName: "",
        ServiceProviderID: "",
        ServiceBank: "",
        // ServiceBankId: null,
        ServiceAccountNo: "",
        PayChannelId: "",

        // MID: "客户",
        MID: "",
        CustomerName: "",
        TSKID: "",
        // _agentname: "客户名称",
        RechargeRate: "",
        ruleType: "",
        RechargeTime: new Date(),
        AccountAmount: "",
        RechargeAmount: "",
        // _rechargetime: "充值时间",
        // RechargeStatus: "充值状态",
        QZDRate: "",
        Rate: "",
        Note: "",
        customerReceiptUrl: "",
      },
      addFormKeys: {
        MID: "客户",
        TSKID: "",
        ServiceProviderName: "",
        ServiceBank: "",
        ServiceAccountNo: "",
        PayChannelId: "",

        RechargeRate: "",
        ruleType: "",
        RechargeTime: "",
        AccountAmount: "",
        RechargeAmount: "",
        Note: "",
        customerReceiptUrl: "",
      },
      task: {},
    };
  },
  watch: {
    "addForm.ServiceProviderID": {
      handler(newValue) {
        this.getServiceBanks(newValue);
        // this.getRate();
        // this.merchantApiName = `/api/Common/GetMerchantList?sid=${newValue}`;
      },
    },
    "addForm.MID": {
      handler() {
        // this.getRate();
        this.tskIdApi = `/api/ServiceProject/GetList?mid=${this.addForm.MID}`;
      },
    },
    "addForm.TSKID": {
      handler() {},
    },
    "addForm.RechargeRate": {
      handler(newValue) {
        this.rechargeRateChange(newValue);
      },
    },
  },
  created() {
    let { row, apiName, TSKID } = this.$route.params;
    if (row) {
      this.addForm = { ...row };
    }

    console.log(this.addForm);
    if (apiName) {
      this.api = new API(apiName);
    }
    if (TSKID) {
      this.addForm.TSKID = TSKID;
    }
  },
  mounted() {
    // this.addForm["TSKID"] = this.addForm["SPID"] || this.addForm["TSKID"];
  },
  methods: {
    serviceChange(e) {
      console.log(1);
      if (!e) {
        return;
      }
      let data = {
        ServiceBank: "",
        ServiceAccountNo: "",
        PayChannelId: "",
        CustomerName: "",
        RechargeRate: "",
        QZDRate: "",
        Rate: "",
        MID: "",
      };
      this.addForm = { ...this.addForm, ...data };
      this.addForm.ServiceProviderID = e.Id;
    },
    serviceBankChange(e) {
      if (!e) {
        return;
      }
      this.addForm.ServiceBankId = e.Id;
      this.addForm.ServiceAccountNo = e.AcctNo;
    },
    async getServiceBanks(sid) {
      if (!sid) {
        return;
      }
      let response = await this.$http.get(
        `/api/recharge/GetServiceBank?sid=${sid}`
      );

      this.serviceBanks = response.data.Data.accountlist;
      this.payChannelList = response.data.Data.paychannellist;
    },

    async midChange(res) {
      if (!res) {
        return;
      }
      this.addForm = {
        ...this.addForm,
        ruleType: res.ruleType,
        // RechargeAmount: "",
        // AccountAmount: "",
        QZDRate: res.QZDRate,
        Rate: res.Rate,
        RechargeRate: res.Rate,
        ServiceProviderID: res.ServiceId,
        ServiceProviderName: res.ServiceName,
      };

      this.addForm.CustomerName = res.MerchantName;
      // this.addForm.MID = res.Id;
    },

    taskIdChange(item) {
      // this.accountChange(item.Amount);

      if (item) {
      //  this.addForm.AccountAmount = item.Amount;
        this.addForm.MID = item.MID;
        // this.accountChange(item.Amount);
      }
      this.task = item;
    },

    async getRate() {
      let { MID: mid, ServiceProviderID: sid } = this.addForm;
      if (!mid || !sid) {
        return;
      }
      let query = { mid, sid };
      let response = await this.$http.get(
        "/api/recharge/GetMerchantBank",
        query
      );
      let payInfo = response.data.Data;
      this.addForm.PayingAccountName = payInfo[0].PayingAccountName;
      this.addForm.PayingBank = payInfo[0].PayingBankName;
      this.addForm.PayingAccount = payInfo[0].PayingAccount;
      this.addForm.Rate = Number(payInfo[0].Rate);
      this.addForm.RechargeRate = Number(payInfo[0].Rate);
      this.addForm.QZDRate = Number(payInfo[0].QZDRate);
      this.addForm.ruleType = payInfo[0].Rule;
      if (this.task.Amount) {
        this.accountChange(this.task.Amount);
      }
    },
    rechargeRateChange() {
      let recharge = this.addForm.RechargeAmount;
      let account = this.addForm.AccountAmount;
      if (account) {
        this.accountChange(account);
      } else if (recharge) {
        this.rechargeChange(recharge);
      }
    },
    ruleTypeChange() {
      this.rechargeRateChange();
      // let ruleTyple = e || this.addForm.ruleTyple;
    },
    rechargeChange(value) {
      this.addForm.AccountAmount = this.calcAccount({
        ruleType: this.addForm.ruleType,
        rate: this.addForm.RechargeRate,
        recharge: value,
      });
      this.addForm.RechargeAmount = this.toFixed2(value);
    },
    accountChange(value) {
      this.addForm.RechargeAmount = this.calcRecharge({
        ruleType: this.addForm.ruleType,
        rate: this.addForm.RechargeRate,
        account: value,
      });
      this.addForm.AccountAmount = this.toFixed2(value);
    },
    calcAccount({ ruleType, rate, recharge }) {
      rate /= 100;
      let res = 0;
      if (ruleType == "A") {
        res = recharge * (1 - rate);
      } else {
        res = recharge / (1 + rate);
      }
      return res.toFixed(2);
    },
    calcRecharge({ ruleType, rate, account }) {
      rate /= 100;
      let res = 0;
      if (ruleType == "A") {
        res = account / (1 - rate);
      } else {
        res = account * (1 + rate);
      }
      return res.toFixed(2);
    },
    amountInputTips() {
      return this.addForm.RechargeRate ? "" : "请先选择服务费率";
    },
    async onSubmit(formName) {
      console.log(formName);
      console.log(this.api.fullName);
      console.log(this.addForm);
      const valided = await this.$refs[formName].validate().catch((err) => err);
      if (!valided) {
        return;
      }
      let response;
      if (this.api.action === "Check") {
        response = await this.$http.post(
          `${this.api.check}${this.addForm.Id}?RechargeStatus=${this.checkStatus}`
        );
      } else {
        response = await this.$http.post(this.api.fullName, this.addForm);
      }
      console.log(response);
      // this.$message.success(response.data.Message);
      this.$router.replace("/recharge");
    },
    cancelfunc (){
      // this.$store.dispatch("PayDetail", this.$route);
      this.$router.go(-1);

    }
  },
};
</script>

<style lang="less" scoped>
.row {
  align-items: flex-start;
  .left {
    padding: 0 1rem;
  }
}
</style>
